﻿module Extensions

open System.Xml
open System.Xml.Linq

type XElement with
    member e.Element(str:string) =
        e.Element(XName.Get(str))
    member e.Elements(str) =
        e.Elements(XName.Get(str))
    member e.Element(str:string,predicate:XElement->bool) =
        e.Elements(str) |> Seq.find predicate
    member e.Attribute str=
        e.Attribute(XName.Get str)
    member e.Attribute(str:string,predicate)=
        e.Attributes(XName.Get str) |> Seq.find predicate
//    member e.ReadUserPassword()=
//        let pwdElement =
//            e.Elements(XName.Get("Option"))
//            |> Seq.find ( fun ( elemnt:XElement) ->  elemnt.Attribute(XName.Get("Name")).Value="Pass")
//        pwdElement.Value
    member user.updateUser  findFunc (updateFunc:XElement->unit)=
        let e = user |> findFunc
        updateFunc e
    member user.updateUserPassword  newPwd=
        let findf (x:XElement) =
            x.Elements(XName.Get("Option"))
            |> Seq.find (fun (e:XElement) -> e.Attribute(XName.Get("Name")).Value="Pass")
        let updatef (x:XElement) =
            x.Value<-newPwd
        user.updateUser findf updatef

    ///添加流畅接口
type XDocument with
    member doc.Element(str:string) =
        doc.Element(XName.Get(str))
    member doc.Elements(str) =
        doc.Elements(XName.Get(str))
    member doc.Element(str:string,predicate:XElement->bool) =
        doc.Elements(str) |> Seq.find predicate
    member doc.findGroup groupName =
        doc.Element("FileZillaServer").Element("Groups").Element("Group",fun e->e.Attribute("Name").Value= "YLs")

    member doc.findUser  name =
        doc.Element("FileZillaServer" ).Element("Users").Element("User",fun u->u.Attribute("Name").Value=name)
    ///替换现在名字相同的用户
    member doc.addUser (user:XElement) =
        let root =doc.Element("FileZillaServer").Element("Users")
        let users = root.Elements("User") 
        users |> Seq.iter (fun u ->if  u.Attribute("Name") =user.Attribute("Name") then u.Remove())
        root.AddFirst(user)

